#!/usr/bin/env python3
# _*_coding:utf-8 _*_
__author__ = "Gao"
'''权限验证'''

from django.shortcuts import HttpResponse
from django.urls import resolve
import re

from . import permission_list


def check_permission(func):
    '''验证权限装饰器'''
    def wrapper(request, *args, **kwargs):
        if not perm_check(request, *args, **kwargs):
            return  HttpResponse(status=403)
        else:
            return func(request,*args, **kwargs)
    return wrapper


def perm_check(request, *args, **kwargs):
    '''检查用户是否有权限访问当前Url'''
    if request.user.is_authenticated:    # 判断用户是否登录
        for permission_name,v in permission_list.perm_dict.items():
            url_matched = False    # 进行Url匹配
            if v['url_type'] == 0:
                resolve_url = resolve(request.path)    # 将请求的Url反解成Url别名
                if resolve_url.url_name == v['url']:
                    url_matched = True
            elif v['url_type'] == 1:
                if request.path == v['url']:
                    url_matched = True
            elif v['url_type'] == 2:
                if re.search(v['url'],request.path):
                    url_matched = True
            if url_matched:
                if request.method == v['method']:    # 匹配请求方法
                    arg_matched = True    # 进行请求参数匹配，如果未配置参数规则，默认为True
                    if len(v['args']) >0:
                        request_method_func = getattr(request, v['method'])
                        for request_arg in request_method_func.keys():
                            if not request_arg in v['args']:
                                arg_matched = False
                    if request.method == 'POST':
                        if len(v['file_args']) > 0:
                            for file_arg in request.FILES.keys():
                                if not file_arg in v['file_args']:
                                    arg_matched = False
                    if arg_matched:
                        # 通过Url、method和Args，找到自定的规则项
                        if request.user.has_perm(permission_name):
                            # 判断该用户权限中是否有该规则项
                            func_checked = True    # 使用自定义函数做进一步验证
                            for func in v['hooks']:
                                if func(request, *args, **kwargs) == False:
                                    func_checked = False
                                    break
                            return func_checked
                        else:
                            return False
    return False
